package com.example.spring.boot.rabbitmq.configuration;

import com.example.spring.boot.rabbitmq.constant.DelayExchangeConstant;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 延迟队列配置类
 * </p>
 *
 * @author weixin
 * @date 2023/3/28 14:12
 */
@Configuration
public class DelayExchangeConfig {

    /**
     * 定义延迟队列
     */
    @Bean
    public Queue delayQueue() {
        return QueueBuilder.durable(DelayExchangeConstant.DELAY_QUEUE).build();
    }

    /**
     * 定义延迟交换机
     */
    @Bean
    public Exchange delayExchange() {
        Map<String, Object> args = new HashMap<>(2);
        args.put("x-delayed-type", "direct");
        return ExchangeBuilder
                .directExchange(DelayExchangeConstant.DELAY_EXCHANGE)
                .delayed()
                .withArguments(args)
                .build();
    }


    /**
     * 绑定延迟队列到延迟交换机
     * @return {@link Binding}
     */
    @Bean
    public Binding delayBinding(Queue delayQueue, Exchange delayExchange) {
        return BindingBuilder
                .bind(delayQueue)
                .to(delayExchange)
                .with(DelayExchangeConstant.DELAY_ROUTING_KEY)
                .noargs();
    }

}
